<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NEllipsis,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NPopconfirm, NSelect,
  NSwitch,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {router} from "@/router";
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"


defineOptions({ name: '会员资金' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '会员资金',
  initForm: {},
  doCreate: api.createCustomer,//接口地址修改
  doUpdate: api.updateCustomer,//接口地址修改
  doDelete: api.deleteCustomer,//接口地址修改
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  platform_options: [
    { label: '小程序', value: 1 },
    { label: 'IOS', value: 2 },
    { label: '安卓', value: 3 },
  ],
  sex_options: [
    { label: '男', value: 1 },
    { label: '女', value: 2 },
  ],
  customer_level: [],
  token: getToken(),
  uploadAction: base_path+'api/customer/users/file',
  onLevelData: [],
  selectValue:'',
  show_excel:false,
});

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

onMounted(() => {
  getcosutomer_level()
  $table.value?.handleSearch()
})

//表单规则部分
const addAPIRules = {
  name: [
    {
      required: true,
      message: '请输入会员昵称',
      trigger: ['input', 'blur'],
    },
  ],
  role_id: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
}

//table表头
const columns = [
    {
    title: 'ID',
    key: 'id',
    align: 'center',
    width: '70',
    ellipsis: { tooltip: true },
  },
  {
    title: '卡号',
    key: 'card_no',
    align: 'center',
    width: '70',
    ellipsis: { tooltip: true },
  },
  {
    title: '头像/昵称',
    key: 'avatar',
    width: '150',
    align: 'left',
    ellipsis: { tooltip: true },
    fixed: 'left',
    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.avatar,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary"
        }, {
          default: () => (row.name)
        })]
      )

    },
  },
  {
    title: '会员级别',
    key: 'role_name',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '真实姓名',
    key: 'alias',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
      {
    title: '储值金',
    key: 'money_deposit',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.money_deposit }
      )
    },
  },
      {
    title: '积分',
    key: 'money_integral',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.money_integral }
      )
    },
  },
      {
    title: '优惠券',
    key: 'money_coupons',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.money_coupons }
      )
    },
  },
      {
    title: '佣金',
    key: 'money_commission',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.money_commission }
      )
    },
  },
     {
    title: '成长积分',
    key: 'level_integral',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.level_integral }
      )
    },
  }


]

//上传头像
const message = useMessage();


//获取默认会员类型
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}

//获取上级部门id
async function onleves(query) {
  let val = await api.getLeves({key:query})
  data.onLevelData = val.data
}

//异步下拉获取上级
const loadingRef = ref(false);
const optionsRef = ref([]);
const handleLeves = (query) => {
  if (!query.length) {
    optionsRef.value = [];
    return;
  }
  onleves(query)
  loadingRef.value = true;
  // data.selectValue
  window.setTimeout(() => {
    data.onLevelData.value = data.onLevelData.filter(
      (item) => ~item.label.indexOf(query)
    );
    loadingRef.value = false;
  }, 1e3);
}



</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="会员资金">
    <template #action>
      <div>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getCustomer">
      <template #queryBar>
        <QueryBarItem label="会员昵称" :label-width="70">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入会员姓名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="会员卡号" :label-width="70">
          <NInput v-model:value="queryItems.card_no" clearable type="text" placeholder="请输入卡号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="会员类型" :label-width="70">
          <NSelect
            v-model:value="queryItems.role_id"
            style="width: 150px"
            :options="data.customer_level"
            clearable
            placeholder="请选会员类型"
          />
        </QueryBarItem>
        <QueryBarItem label="上级昵称" :label-width="70">
          <NInput v-model:value="queryItems.parent_name" clearable type="text" placeholder="请输入上级姓名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="上级卡号" :label-width="70">
          <NInput v-model:value="queryItems.parent_card_no" clearable type="text" placeholder="请输入上级卡号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="手机号码" :label-width="70">
          <NInput v-model:value="queryItems.phone" clearable type="text" placeholder="请输入手机号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="创建时间" :label-width="70">
          <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
            @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

  </CommonPage>
</template>
